<script lang="ts" setup>
import { ref } from 'vue';
import { useFetch } from '@/mobile/hooks/fetch';
import { getAdPositions } from '@/mobile/utils/format';

import InfiniteScroll from '@/mobile/components/InfiniteScroll.vue';
import RecommendArticle from './RecommendArticle.vue';
import Operation from './Operation.vue';

const { $fetch } = useFetch();
const listing = ref<any>([]);
const operators = ref<any>([]);

let page = 1;
const loading = ref(false);
const finished = ref(false);

// 初始化广告位
const operateId = ref(0);
const adPositions = ref<number[]>([]);

// 加载更多数据
const loadMoreData = async () => {
  if (finished.value) { return; }

  loading.value = true;

  // 请求推荐列表和广告
  const [recommendResult, adResult] = await Promise.all([
    $fetch('/information/home_info_list', { method: 'post', data: { pageNum: page, pageSize: 10 } }),
    $fetch('/operator/queryAdvertisements', { method: 'post', data: { preOperatorId: operateId.value, pageSize: 1 } }),
  ]);

  // 如果推荐数据成功返回并且有内容
  if (recommendResult?.isSuccess && recommendResult?.data?.records?.length) {
    listing.value.push(...recommendResult.data.records);
    if (adResult.data?.length) {
      operateId.value = adResult.data.slice(-1)[0].operateId;
      // 将广告数据存入 operators 数组
      operators.value.push(...adResult.data);
      adPositions.value.push(getAdPositions(listing.value.length, recommendResult.data.records.length))
    }
    page++;
  } else {
    finished.value = true;
  }

  loading.value = false;
};

const removeAd = (index: number) => {
  const indexof = adPositions.value.indexOf(index);
  operators.value.splice(indexof, 1);
  // 更新 adPositions 数组
  adPositions.value.splice(indexof, 1);
}
</script>

<template>
  <section>
    <InfiniteScroll v-model:loading="loading" :finished="finished" @load="loadMoreData">
      <li v-for="(item, index) in listing" :key="index" class="bg-[#fff] px-20">
        <RecommendArticle :data="item" />
        <Operation v-if="adPositions.includes(index)" :data="operators[adPositions.indexOf(index)]" @close="removeAd(index)" />
      </li>
    </InfiniteScroll>
  </section>
</template>

<style lang="scss" scoped>
li div:last-child {
  border-bottom: 0;
}
</style>
